package com.acmen.easyapi.repository;

import com.acmen.easyapi.dbcp.JdbcService;
import com.acmen.easyapi.model.TestReport;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

;

/**
 * @author acmen
 */
@Component
public class TestReportRepository {

    private final static String QUERY_SQL = "select * from t_test_report where test_id=? order by create_dt desc";
    private final static String QUERY_SINGLE_ROW_SQL = "select * from t_test_report where id=? ";
    private final static String INSERT_SQL = "insert into t_test_report(id,test_id,api_id,api_name,path,method,total,total_cost,min_cost,max_cost,avg_cost,send_size,receive_size,response_success_num,business_success_num) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    private final static String DELETE_SQL = "delete from t_test_report where id=?";
    @Resource
    private JdbcService jdbcService;

    /**
     * 根据应用ID查询出记录
     * @param pressureTestId
     * @return
     */
    public List<TestReport> selectList(String pressureTestId) {
        List<TestReport> aggregateReports = jdbcService.selectList(QUERY_SQL, new Object[]{pressureTestId}, TestReport.class);
        return aggregateReports;
    }

    public TestReport selectOne(String id){
        TestReport aggregateReport =  jdbcService.selectOne(QUERY_SINGLE_ROW_SQL, new Object[]{id}, TestReport.class);
        return aggregateReport;
    }

    /**
     * 保存结果
     *
     * @param aggregateReports
     * @return
     */
    public void batchCreate(List<TestReport> aggregateReports) {
        List<Object[]> batchArgs=new ArrayList<>();
        aggregateReports.forEach(aggregateReport->{
            Object[] args = {aggregateReport.getId(), aggregateReport.getTestId(),
                    aggregateReport.getApiId(),aggregateReport.getApiName(), aggregateReport.getPath(), aggregateReport.getMethod(),
                    aggregateReport.getTotal(),aggregateReport.getTotalCost(),aggregateReport.getMinCost(), aggregateReport.getMaxCost(),
                    aggregateReport.getAvgCost(),aggregateReport.getSendSize(),aggregateReport.getReceiveSize(),
                    aggregateReport.getResponseSuccessNum(),aggregateReport.getBusinessSuccessNum()};
            batchArgs.add(args);
        });
        jdbcService.batchUpdate(INSERT_SQL, batchArgs);
    }

    /**
     * 删除组合测试
     *
     * @param id
     * @return
     */
    public boolean delete(String id) {
        return jdbcService.update(DELETE_SQL, new Object[]{id}) > 0;
    }

}
